<script setup>
import {ref, reactive, watch, nextTick} from 'vue'

const props = defineProps({
    modelValue: {
        type: String,
        required: true,
        default: '',
    }
})
const emits = defineEmits(['update:modelValue', 'send'])

//#region 变量定义
const textareaRef = ref(null)
const textareaStyle = reactive({height: '20px'});
//#endregion

watch(() => props.modelValue, (newValue, oldValue) => {
    // 下面代码用于动态控制输入框高度
    let textDom = textareaRef.value
    let scrollHeight = textDom.scrollHeight
    let offsetHeight = textDom.offsetHeight
    if (scrollHeight === offsetHeight) {
        textareaStyle.height = `20px`
    }
    nextTick(() => {
        scrollHeight = textDom.scrollHeight
        offsetHeight = textDom.offsetHeight
        if (scrollHeight > 0 && scrollHeight > textDom.offsetHeight && scrollHeight < 300 - 20) {
            textareaStyle.height = `${scrollHeight - 20}px`
        }
    })
})

//#region 方法定义
/**
 * 输入框输入回调，更新modelValue
 * @param e
 */
const change = (e) => {
    emits('update:modelValue', e.target.value)
}

/**
 * 敲回车或者点击发送按钮
 * @param e
 */
const submit = (e) => {
    emits('send', props.modelValue)
}
//#endregion

</script>

<template>
    <div class="chat-input-container">
        <div class="chat-input-action"></div>
        <textarea ref="textareaRef" class="chat-input-message" :style="textareaStyle" :value="modelValue"
                  @input="change"
                  @keydown.enter.stop.prevent="submit"/>
        <!--        <button type="button" class="chat-input-send-btn">发送</button>-->
        <slot name="submit">
            <el-button type="primary" class="chat-input-send-btn" @click="submit" :disabled="!modelValue">
                发送
                <el-icon class="el-icon--right">
                    <Promotion/>
                </el-icon>
            </el-button>
        </slot>
    </div>
</template>

<style scoped lang="scss">
.chat-input-container {
    position: relative;
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    border-radius: 15px;
    border: 1px solid rgba(28, 31, 35, 0.08);
    padding: 10px 20px;

    .chat-input-action {

    }

    .chat-input-message {
        flex: 1;
        min-width: 1px;
        border: none;
        outline: none;
        background: none;
        resize: none;
        line-height: 20px;
        height: 20px;
        box-sizing: content-box;
        font-size: 14px;
        padding: 10px 20px;
        vertical-align: bottom;
        cursor: text;
        font-family: "Microsoft YaHei", serif;
    }

    .chat-input-send-btn {
        //width: 80px;
        //height: 45px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}
</style>